﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using QuanLyDeTaiKHCN.Obj_class;
using System.IO;
using System.Configuration;

namespace QuanLyDeTaiKHCN.UserControls.Manager
{
    public partial class NhanHoSoThuyetMinh : System.Web.UI.UserControl
    {
        _dbDataContext _db = new _dbDataContext();
        public SecurityLib.Sec_AES _se = new SecurityLib.Sec_AES();
        public string domain_name = ConfigurationManager.AppSettings["url"];
        public string directory = ConfigurationManager.AppSettings["directory"];
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                CatalogAccess.BindDatatoDropList(2, drlHocHamHocVi);
                BindData();
            }
        }
        protected void BindData()
        {
            string st = Request.QueryString["id"];
            if (st != null)
            {
                st = st.Replace(" ","+");
                string madetai = _se.Decrypt(st,"gold",128);
                var list = _db.tblDanhSachDeTaiDuAns.Single(r=>r.MaDeTaiDuAn.Trim()==madetai);
                txtMaDeTai.Text = list.MaDeTaiDuAn.Trim();
                if (list.Loai == 1)
                    rddetai.Checked = true;
                else
                    rdduan.Checked = true;
                if (list.LoaiHoSo == 1)
                    rdnhanthuyetminh.Checked = true;
                else
                    rdnhanhoso.Checked = true;
                if (list.LinhVuc == 1)
                    rdbtunhien.Checked = true;
                else
                    rdbxahoi.Checked = true;
                txtTenDeTai.Text = list.TenDeTaiDuAn.Trim();
                txtThucHienTu.Text = string.Format("{0:dd/MM/yyyy}",list.ThoiGianThucHienTu);
                txtThucHienDen.Text = string.Format("{0:dd/MM/yyyy}", list.ThoiGianThucHienDen);
                txtTongKinhPhi.Text = list.TongKinhPhi.ToString();
                txtTuNganSach.Text = list.TuNganSach.ToString();
                txtNguonVonKhac.Text = list.NguonVonKhac.ToString();
                try
                {
                    txtNamBanHanhDanhMuc.Text = list.ThoiGianBanHanhDanhMuc.Trim();
                }
                catch { }
                try
                {
                    txtThuocChuongTrinh.Text = list.ThuocChuongTrinh.Trim();
                }
                catch { }
                try
                {
                    txtHoTenChuNhiemDeTai.Text = list.ChuNhiemDeTai.Trim();
                }
                catch { }
                drlHocHamHocVi.SelectedValue = list.HocHamHocVi.ToString();
                try
                {
                    txtDienThoaiNhaRieng.Text = list.DienThoaiNhaRieng.Trim();
                }
                catch { }
                try
                {
                    txtDienThoaiCoQuan.Text = list.DienThoaiCoQuan.Trim();
                }
                catch { }
                try
                {
                    txtDienThoaiDiDong.Text = list.DienThoaiDiDong.Trim();
                }
                catch { }
                try
                {
                    txtEmail.Text = list.Email.Trim();
                }
                catch { }
                try
                {
                    txtTenDonVi.Text = list.TenDonViChuTri.Trim();
                }
                catch { }
                try
                {
                    txtDiaChi.Text = list.DiaChiDonVi.Trim();
                }
                catch { }
                try
                {
                    txtDienThoaiDonVi.Text = list.DienThoaiDonVi.Trim();
                }
                catch { }
                try
                {
                    txtFax.Text = list.FaxDonVi.Trim();
                    
                }
                catch { }
                BindGrid(madetai);
            }
        }
        protected void BindGrid(string madetai)
        {
            var list = from p in _db.tblFiles.Where(r => r.MaDeTaiDuAn.Trim() == madetai && r.FileCuaBuoc==1)
                       select new
                       {
                           ID=p.ID,
                           TrichYeu=p.GhiChuFileThuyetMinh.Trim(),
                           NgayLuu=string.Format("{0:dd/MM/yyyy}",p.NgayNhanThuyetMinh),
                           FileThuyetMinh=p.FileThuyetMinh.Trim(),
                           //sau khi up len host thi xai link1:
                           //Fileonline =domain_name + "\\" +directory+"\\"+ p.FileThuyetMinh.Trim()
                           //test xaif link2
                            //Fileonline = "localhost\\" +directory+"\\"+ p.FileThuyetMinh.Trim()
                            //demo link3:
                            Fileonline="http://thongkekhcnbd.khcnbinhduong.gov.vn/userfiles/vanban/9475707965_493_296.pdf"
                           
                       };
            grid.DataSource = list.ToList();
            grid.DataBind();
        }
        protected void btnsave_Click(object sender, EventArgs e)
        {
            int tungay = _db.Tinhsongay(CatalogAccess.ConvertToDate(txtThucHienTu.Text));
            int denngay = _db.Tinhsongay(CatalogAccess.ConvertToDate(txtThucHienDen.Text));
            if (tungay >= denngay)
            {
                lblstatus.Text = "Thời gian thực hiện không hợp lệ (Từ ngày phải nhỏ hơn đến ngày)";
                return;
            }
            int loai = 1;
            if (rddetai.Checked == true)
            {
                loai = 1;//de tai
            }
            else
            {
                loai = 2;//du an
            }
            int linhvuc = 1;
            if (rdbtunhien.Checked == true)
                linhvuc = 1;
            else
                linhvuc = 2;
            int loaihoso = 1;
            if (rdnhanthuyetminh.Checked == true)
            {
                loaihoso = 1;//nhan thuyet minh
            }
            else
            {
                loaihoso = 2;//xet chon ho so
            }
            int tongkinhphi = 0;
            int tungansach = 0;
            int nguonvonkhac = 0;
            try { tongkinhphi = int.Parse(txtTongKinhPhi.Text); }
            catch { }
            try { tungansach = int.Parse(txtTuNganSach.Text); }
            catch { }
            try { nguonvonkhac = int.Parse(txtNguonVonKhac.Text); }
            catch { }
            if (tongkinhphi != tungansach + nguonvonkhac)
            {
                lblstatus.Text = "Tổng kinh phí phải bằng tổng kinh phí từ ngân sách cộng với nguồn vốn khác";
                return;
            }
            bool success = CatalogAccess.CapNhatThongTinDeTai(txtMaDeTai.Text, loai,linhvuc, txtTenDeTai.Text, txtThucHienTu.Text, txtThucHienDen.Text, tongkinhphi,
                tungansach, nguonvonkhac, txtThuocChuongTrinh.Text, txtHoTenChuNhiemDeTai.Text,
                int.Parse(drlHocHamHocVi.SelectedValue.ToString()), txtDienThoaiCoQuan.Text, txtDienThoaiNhaRieng.Text, txtDienThoaiDiDong.Text,
                txtEmail.Text, txtTenDonVi.Text, txtDiaChi.Text, txtDienThoaiDonVi.Text, txtFax.Text, loaihoso, CatalogAccess.GetUserID(this.Page.User.Identity.Name),txtNamBanHanhDanhMuc.Text);
            if (success)
            {
                lblstatus.Text = "Đã lưu hồ sơ.";
            }
            else
            {
                lblstatus.Text = "Không lưu được hồ sơ, hãy thử lại.";
            }
        }

        protected void LinkAddFile_Click(object sender, EventArgs e)
        {
            if (_db.tblFiles.Where(r => r.MaDeTaiDuAn.Trim() == txtMaDeTai.Text && r.FileCuaBuoc==1).Count() > 1)
            {
                lblmessage.Visible = true;
                lblmessage.Text = "Chỉ upload 2 file thuyết minh.";
            }
            else
            {
                lblmessage.Text = "";
                lblmessage.Visible = false;
                if (filethuyetminhdetai.HasFile)
                {
                    DateTime t = DateTime.Now;
                    string filename = (t.Day < 10 ? "0" + t.Day.ToString() : t.Day.ToString()) + (t.Month < 10 ? "0" + t.Month.ToString() : t.Month.ToString()) + t.Year.ToString() + t.Hour.ToString() + t.Minute.ToString() + t.Second.ToString() + Path.GetExtension(filethuyetminhdetai.FileName);
                    tblFile _tb = new tblFile();
                    _tb.MaDeTaiDuAn = txtMaDeTai.Text;
                    _tb.FileThuyetMinh = filename;
                    _tb.GhiChuFileThuyetMinh = txtghichufilethuyetminh.Text;
                    _tb.NgayNhanThuyetMinh = CatalogAccess.ConvertToDate(txtNgayNhanThuyetMinhDeCuong.Text);
                    _tb.FileCuaBuoc = 1;
                    try
                    {
                        _db.tblFiles.InsertOnSubmit(_tb);
                        _db.SubmitChanges();
                        BindGrid(txtMaDeTai.Text.Trim());
                        filethuyetminhdetai.SaveAs(Server.MapPath(PageURL.local + "filehoso/" + filename));
                        txtghichufilethuyetminh.Text = "";
                    }
                    catch { }
                }
            }
        }

        protected void grid_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            var item = _db.tblFiles.Single(r => r.ID == int.Parse(grid.DataKeys[e.RowIndex].Value.ToString()));
            try
            {
                _db.tblFiles.DeleteOnSubmit(item);
                _db.SubmitChanges();
                try
                {
                    string filename = ((Label)grid.Rows[e.RowIndex].FindControl("lblFileName")).Text;
                    System.IO.File.Delete(Server.MapPath(PageURL.local + "filehoso/" + filename));
                }
                catch { }
                BindGrid(txtMaDeTai.Text.Trim());
            }
            catch { }
        }

        //protected void aaa_Click(object sender, EventArgs e)
        //{
        //    Label lbcsslbl;
        //    Label lbcsstxt;
        //    Panel pfile;
        //    Panel ptext;
        //    FileUpload file;
        //    TextBox txt;
        //    for (int i = 0; i < 5; i++)
        //    {
        //        lbcsslbl = new Label();
        //        lbcsslbl.Text = "<div style=height: 5px;clear:both;></div>";
        //        lbcsslbl.Text+="<label class=control-label style=padding-right: 10px;>File</label>";
        //        lbcsslbl.Text += "<div class=controls>";
        //        pfile = new Panel();
        //        file = new FileUpload();
        //        pfile.ID = "pn"+i.ToString();
        //        pfile.Controls.Add(lbcsslbl);
        //        pfile.Controls.Add(file);
        //        lbcsslbl = new Label();
        //        lbcsslbl.Text = "</div>";
        //        pfile.Controls.Add(lbcsslbl);
        //        p1.Controls.Add(pfile);
        //        //=============them text box==========
        //        lbcsstxt = new Label();
        //        lbcsstxt.Text = "<div style=height: 5px;clear:both;></div>";
        //        lbcsstxt.Text += "<label class=control-label style=padding-right: 10px;>Ghi chu</label>";
        //        lbcsstxt.Text += "<div class=controls>";
        //        ptext = new Panel();
        //        ptext.Controls.Add(lbcsstxt);
        //        txt = new TextBox();
        //        txt.ID = "txt" + i.ToString();
        //        txt.CssClass = "span12";
        //        txt.Height = 100;
        //        txt.TextMode = TextBoxMode.MultiLine;
        //        ptext.ID = "pntxt" + i.ToString();
        //        ptext.Controls.Add(txt);
        //        lbcsstxt = new Label();
        //        lbcsstxt.Text = "</div>";
        //        ptext.Controls.Add(lbcsstxt);
        //        p1.Controls.Add(ptext);
        //    }
        //}
        
    }
}